//
//  MTCompanyAuthController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/30.
//  Copyright © 2020 张强. All rights reserved.
//

import Moya
import Result
import RxSwift
import RxCocoa
import MTCategory

class MTCompanyAuthController: BaseViewController {
    
    /// MTProvider
    private lazy var provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    var model: MTCerSummarySubModel? {
        didSet {
            contactName = model?.companyCertification?.userName
            contactPhone = model?.companyCertification?.mobile
            imageUrl = model?.companyCertification?.href
        }
    }
    
    /// 列表控制数组
    private var infoTypes: [[UserProfileInfos]] = [[.license],
                                                   [.contactName, .contactPhone]]
    
    ///营业执照
    var imageUrl: String?
    ///联系人
    var contactName: String?
    
    ///联系电话
    var contactPhone: String?
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .grouped)
        tv.delegate = self
        tv.dataSource = self
        tv.separatorStyle = .none
        tv.keyboardDismissMode = .onDrag
        tv.showsVerticalScrollIndicator = false
        tv.tableFooterView = UIView()
        tv.backgroundColor = UIColor(hex: 0xf6f6f6)
        
        for types in infoTypes {
            for type in types {
                tv.register(type.cellClass, forCellReuseIdentifier: String(describing: type.cellClass))
            }
        }

        return tv
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("提交申请", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(companyAuthController(didClickCommitButton:)), for: .touchUpInside)
        return btn
    }()
    
    deinit {
        removeNotifications()
    }
    
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTCompanyAuthController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifications()
//        loadData()
        initializeUI()
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTCompanyAuthController {
    
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "商家认证"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        view.addSubview(commitButton)
        commitButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MTCompanyAuthController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
    
}

// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MTCompanyAuthController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return infoTypes.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoTypes[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return infoTypes[indexPath.section][indexPath.row].cellHeight
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let type = infoTypes[indexPath.section][indexPath.row]
        let c = tableView.dequeueReusableCell(withIdentifier: String(describing: type.cellClass), for: indexPath)

        switch type {

        case .license:
            guard let cell = c as? MTInfoVerificationPortraitCell else {
                break
            }
//            cell.delegate = self
//            cell.models = self.imgList
            cell.type = type
            cell.loadURL = imageUrl
            return cell
        case .contactName, .contactPhone:
            guard let cell = c as? MTInfoVerificationInputCell else {
                break
            }
            cell.delegate = self
            cell.screenMode = 1
            cell.textFieldTextAlignment = .right
            cell.type = type
            if type == .contactName {
                cell.content = contactName
            } else if type == .contactPhone {
                cell.content = contactPhone
            }
            return cell
            
        default: break
        }
        
        return c
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 10))
        view.backgroundColor = UIColor(hex:0xf6f6f6)
        return view
    }
    
}

// MARK: ------------------ input delegate ----------------------
extension MTCompanyAuthController: MTInfoVerificationInputCellDelegate {
    
    func inputCell(_ cell: BaseMTInfoVerificationCell, infoType: UserProfileInfos, didInputText text: String?) {
        switch infoType {
        case .contactName:
            self.contactName = text
            break
        case .contactPhone:
            self.contactPhone = text
            break
        default:
            break
        }
    }
    
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTCompanyAuthController {
    private func companyAuthController(didClickCommitButton sender: UIButton) {
        if imageUrl?.count == 0 {
            AlertManager.presentAlertView(message: "请上传营业执照")
            return
        } else if contactName?.count == 0 {
            AlertManager.presentAlertView(message: "请输入联系人姓名")
            return
        } else if contactPhone?.count == 0 {
            AlertManager.presentAlertView(message: "请输入手机号码")
            return
        } else {
            let params: [String: Any] = ["href"    : imageUrl ?? "",
                                         "mobile"   : contactPhone ?? "",
                                         "userName"   : contactName ?? ""]
            user_provider.rx.requestResult(.companyApply(params)).subscribe(onNext: { [weak self] (result: Result<MTWithdrawReportModel, AnyError>, isCache: Bool) in
                guard let weakself = self else { return }
                switch result {
                case let .success(response):
                    if response.code == 200 {
                        UIAlertController.rx.show(in: weakself, title: "提交成功", message: "审核需要3-5个工作日，请注意查看消息", buttons: [ .default("确定")]).subscribe(onSuccess: {index in
                            if index == 0 {
                                weakself.navigationController?.popToRootViewController(animated: true)
                            }
                        })
                    } else {
                        AlertManager.presentAlertView(message: response.message ?? "")
                    }
                    break
                    
                case let .failure(error):
                    AlertManager.presentAlertView(message: error.localizedDescription)
                    break
                }
            }).disposed(by: disposeBag)
        }
    }
    
}

// MARK: ------------------ 通知相关 ----------------------
extension MTCompanyAuthController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(presentPhotoLibrary), name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }
    
}

// MARK: ------------------------------------ 相册 ----------------------------------------
@objc extension MTCompanyAuthController {
    
    private func presentPhotoLibrary(maxCount: Int, allowVideoSelection: Bool) {
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.maxSelectdCount = 1
        c.allowVideoSelection = allowVideoSelection
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
}

// MARK: ------------------------------------ 相册代理回调 ----------------------------------------
extension MTCompanyAuthController: PhotoLibraryViewControllerDelegate {
        func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
            MTAssetLibrary.default.requestImage(withAsset: asset.asset) { [weak self] (image, info, isDegraded) in
                guard let weakself = self else { return }
                guard let image = image else { return }
                if isDegraded == false {
                    weakself.uploadImage(image: image)
                }
            }
        }
}

extension MTCompanyAuthController {
    private func uploadImage(image: UIImage) {
        /// 添加 indicator
        _ = self.provider.originRequest(.upload(image), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in

            /// 取消 indicator
            guard let weakSelf = self else { return }
            switch result {
            case let .success(response):
                guard let dict = try? response.mapJSON() as? [String:Any], let code = dict["code"] as? Int else { return }
                if code == 200, let imageUrl = dict["result"] as? String  {
                    weakSelf.imageUrl = imageUrl
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                } else {
                    DispatchQueue.main.async {
                        AlertManager.presentAlertView(message: "上传照片失败")
                    }
                }
                break

            case let .failure(error):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break

            }
        }
    }
}


